<template>
  <view
    class="input-controller flex h-full"
    :style="{
      paddingBottom: `${safeAreaInsets?.bottom || 20}px`,
    }"
  >
    <!-- 表达式 盒子 -->
    <view class="exp-container">
      <Expression :inputData="inputData" @btnDelClick="playAudio"></Expression>
    </view>
    <!-- 键盘 盒子 -->
    <view class="kb-wrap w-full">
      <view class="kb-box flex">
        <view
          class="kb-box__col flex flex-col"
          v-for="(colItem, colIndex) in btnColList"
          :key="colIndex"
        >
          <view
            class="kb-box__col__btn-wrap"
            :class="{
              'kb-box__col__btn-wrap_plus': item.value === '+',
            }"
            v-for="(item, index) in colItem"
            :key="index"
          >
            <view
              class="kb-box__col__btn-wrap__content"
              :class="{ 'theme-shadow': calculatorStore.curTheme === 't1' }"
              hover-class="btn_hover"
              :hover-stay-time="100"
              :style="{
                color: item.color,
                background: item.bgColor,
              }"
              @click="handleKeyboardBtnClick(item)"
              @touchstart="handleKeyboardBtnTouchstart"
            >
              {{ item.value }}
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { useCalculatorStore } from '@/store/calculator'

import Expression from './Expression.vue'

const calculatorStore = useCalculatorStore()

// let audioContext = null

// 获取屏幕边界到安全区域距离
const { safeAreaInsets, osName } = uni.getSystemInfoSync()

const bthList = ref<InputController.BtnListItem[]>([
  { value: '1', type: 'num' },
  { value: '2', type: 'num' },
  { value: '3', type: 'num' },
  { value: '4', type: 'num' },
  { value: '5', type: 'num' },
  { value: '6', type: 'num' },
  { value: '7', type: 'num' },
  { value: '8', type: 'num' },
  { value: '9', type: 'num' },
  { value: '0', type: 'num' },
  { value: '00', type: 'num' },
  { value: '.', type: 'num' },
  { value: 'AC', type: 'operator' },
  { value: '+', type: 'operator' },
  { value: '-', type: 'operator' },
  { value: '×', type: 'operator' },
  { value: '÷', type: 'operator' },
  { value: '=', type: 'equal' },
])

const inputData = ref<Expression.InputData>({
  val: '',
  type: 'num',
  timestamp: 0,
})

const formatBtnList = computed(() => {
  return bthList.value.map((item) => {
    const { numColor, numBgColor, operatorColor, operatorBgColor, equalColor, equalBgColor } =
      toRaw(calculatorStore.curThemeOption)
    const typeMap = {
      num: {
        color: numColor,
        bgColor: numBgColor,
      },
      operator: {
        color: operatorColor,
        bgColor: operatorBgColor,
      },
      equal: {
        color: equalColor,
        bgColor: equalBgColor,
      },
    }

    return {
      ...item,
      color: typeMap[item.type].color,
      bgColor: typeMap[item.type].bgColor,
    }
  })
})

const btnColList = computed(() => {
  const list = [
    ['AC', '7', '4', '1', '0'],
    ['÷', '8', '5', '2', '00'],
    ['×', '9', '6', '3', '.'],
    ['-', '+', '='],
  ]
  return list.map((row) => {
    return row.map((item) => {
      return formatBtnList.value.find((btn) => btn.value === item)
    })
  })
})

const handleKeyboardBtnClick = (item) => {
  console.log(
    '%c [ handleKeyboardBtnClick ]-136',
    'font-size:13px; background:pink; color:#bf2c9f;',
    item,
  )
  inputData.value.val = item.value
  inputData.value.type = item.type
  inputData.value.timestamp = Date.now()
}

const handleKeyboardBtnTouchstart = () => {
  playAudio()
  calculatorStore.vibrateShort()
}

const playAudio = () => {
  if (!calculatorStore.openBtnAudio) return
  initAudio()
}

const initAudio = () => {
  const isIos = osName === 'ios'
  let audioContext = uni.createInnerAudioContext({ useWebAudioImplement: isIos })
  // audioContext.src = 'https://cxgxtool.oss-cn-hangzhou.aliyuncs.com/audio/key_bee.mp3'
  audioContext.src = 'https://cxgxtool.oss-cn-hangzhou.aliyuncs.com/audio/key_stone.wav'
  audioContext.autoplay = false
  audioContext.loop = false
  audioContext.volume = 1
  audioContext.playbackRate = 1

  audioContext.onPlay(() => {
    console.log('%c [ onPlay ]: ', 'color: #ffffff; background: red; font-size: 13px;')
  })
  audioContext.onEnded(() => {
    console.log('%c [ onEnded ]: ', 'color: #ffffff; background: green; font-size: 13px;')
    audioContext.destroy()
    audioContext = null
  })
  audioContext.onError((res) => {
    console.log('%c [ onError ]: ', 'color: #ffffff; background: yellow; font-size: 13px;')
  })

  audioContext.play()
}
</script>

<style lang="scss" scoped>
.input-controller {
  flex-direction: column;
  justify-content: flex-end;
}

.btn_hover {
  opacity: 0.5;
}

.kb-wrap {
  $kbGap: 8rpx;

  flex: 1;
  padding: 0 calc(#{$kbGap} * 2);

  .kb-box {
    height: 100%;
    margin: 0 calc(-1 * #{$kbGap});

    .kb-box__col {
      width: 25%;
      height: 100%;

      .kb-box__col__btn-wrap {
        height: 20%;
        padding: $kbGap;

        .kb-box__col__btn-wrap__content {
          display: flex;
          align-items: center;
          justify-content: center;
          // $height: 120rpx;
          height: 100%;
          font-size: 46rpx;
          font-weight: bold;
          border-radius: 10rpx;

          &.theme-shadow {
            box-shadow: 0 2rpx 10rpx 2rpx #00000035;
          }
        }

        &.kb-box__col__btn-wrap_plus {
          flex: 1;
        }
      }
    }
  }
}

.exp-container {
  padding: 0 24rpx;
}
</style>
